package com.ch.ebusiness.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Description TODO
 * @Author MarsYr
 * @Date 2021/5/20 17:55
 * @Version 1.0
 */

@Component
public class RedisUtils {
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    
    public ResultEntity<String> setRedisKeyValue(String key, String value) {
        
        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(key, value);
            return ResultEntity.successWithoutData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
        
    }
    
    
    public ResultEntity<String> setRedisKeyValueWithTimeout(
            String key,
            String value,
            long time,
            TimeUnit timeUnit
    ) {
        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(key, value, time, timeUnit);
            return ResultEntity.successWithoutData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
        
    }
    
    
    public ResultEntity<String> getRedisValueByKey(String key) {
        
        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String value = operations.get(key);
            return ResultEntity.successWithData(value);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
        
        
    }
    
    
    public ResultEntity<String> removeRedisKeyByKey(String key) {
        try {
            stringRedisTemplate.delete(key);
            return ResultEntity.successWithoutData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
        
    }
}

